package cn.kgc.yigou.service;

import cn.kgc.yigou.common.CrowdFundingUtils;
import cn.kgc.yigou.mapper.UserMapper;
import cn.kgc.yigou.pojo.User;
import cn.kgc.yigou.pojo.UserExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Override
    public User login(User user) {
        User users=null;
        UserExample example=new UserExample();
        UserExample.Criteria criteria=example.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        List<User> list =userMapper.selectByExample(example);
        if (list.size()>=1){
            if (list.get(0).getPassword().equals(user.getPassword())){
                users=list.get(0);
            }
        }
        return users;
    }

    @Override
    public int save(User user) {
        int insert= userMapper.insert(user);
        return insert;
    }

    @Override
    public PageInfo<User> queryForKeywordWithPage(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum,pageSize);
      if(CrowdFundingUtils.stringEffective(keyword)) {
          UserExample example=new UserExample();
          UserExample.Criteria criteria=example.createCriteria();
          criteria.andUsernameLike("%"+keyword+"%");
          List<User> list=userMapper.selectByExample(example);
          PageInfo<User> pageInfo=new PageInfo<>(list);
          return pageInfo;
      }else{
          List<User> list=userMapper.selectByExample(null);
          PageInfo<User> pageInfo=new PageInfo<>(list);
          return pageInfo;
      }
    }

    @Override
    public List<User> getUserListByIdList(List<Integer> userIdList) {
        // 创建实体类User对应的Example对象
        UserExample userExample=new UserExample();
        // 在Example对象中封装查询条件
        userExample.createCriteria().andIdIn(userIdList);
        //执行查询
            return userMapper.selectByExample(userExample);
    }

    @Override
    public User selectAllById(int id) {
        return userMapper.selectByPrimaryKey(id);
    }

    //删除
    @Override
    public void batchRemove(List<Integer> userIdList) {
        UserExample example=new UserExample();
        example.createCriteria().andIdIn(userIdList);
        userMapper.deleteByExample(example);

    }

    @Override
    public void updateUser(User user) {
    userMapper.updateByPrimaryKeySelective(user);
    }
}
